from django.db import transaction
from django.http import HttpResponse, JsonResponse
import os
from pathlib import Path
from datetime import datetime

from django.shortcuts import render

from mysqlModel.models import data
from django.views.decorators.csrf import csrf_exempt

from django.contrib.auth.decorators import permission_required


from django.contrib.auth.decorators import user_passes_test, login_required
from django.utils.translation import gettext_lazy as _

def mess(request):
    return render(request, 'err_mess.html')

@csrf_exempt
@permission_required('mysqlModel.delete_data')
def deleteData(request):
    if request.method == 'POST':
        print('222')
        if request.POST['type'] == 'del':
            # 删除id=1的数据
            dataofdelete = data.objects.get(id=request.POST['rid'])
            print(dataofdelete,type(dataofdelete),'data1')
            print(dataofdelete.license.path)
            dataofdelete.delete()
            try:
                os.remove(dataofdelete.license.path)
            except Exception:
                return JsonResponse({'status': False, 'messages': '数据库中这条数据删除成功！\n但是文件夹中没有这个文件'})

        if request.POST['type'] == 're':
            dataofre = data.objects.filter(id=request.POST['rid'])
            dataofre.update(lic_md5='')
            return JsonResponse({'status': True, 'messages': '重新打包成功\n后台已开始构建安装包，完毕后将发送邮件至您的邮箱，请等待~'})
    # 另外一种方式
    # data.objects.filter(id=1).delete()

    # 删除所有数据
    # data.objects.all().delete()

    return JsonResponse({'status': True, 'messages': '数据库数据及对应license文件删除成功！'})



@csrf_exempt
@transaction.atomic
def changestats(request):
    if request.method == "POST":
        try:
            rid = request.POST['rid']
            res = data.objects.get(id=rid)
            # 更新时间做变更
            res.update_time = datetime.now()
            # 对save自动消除特殊字符进行更正,并对相应错误的文件进行更正
            # print(res.license.name,'name11')
            # true_filename = "{}_{}_{}_{}_license.lic".format(res.name,res.soft_version,res.cpu,res.email)
            # if true_filename not in res.license.name:
            #     res.license.name = res.license.name.replace(res.license.name.split('/')[-1].replace('@',''), true_filename)
            #     print(res.license.name,'name22')
            # 获得文件目录
            # BASE_DIR = Path(__file__).resolve().parent.parent
            # 获得license具体文件
            # print(res.license.name,type(res.license.name),'123')
            # old_file_path = os.path.join(BASE_DIR, res.license.name.replace('@',''))
            # if os.path.exists(old_file_path):
            #     new_file_path = os.path.join(BASE_DIR, res.license.name)
            #     print(old_file_path,new_file_path,'pathhere')
            #     # 对文件夹进行更改名字
            #     os.rename(old_file_path, new_file_path)
            print(res.license,type(res.license),res.license.name,'licensename')
            if res.stats == '1':
                res.stats = '4'
                res.save()
                return JsonResponse({'status': True, 'messages': '暂停成功！'})
            elif res.stats == '4':
                res.stats = '0'
                print('444')
                res.save()
                print('555')

                return JsonResponse({'status': True, 'messages': '继续生成中，请耐心等待！'})

        except Exception as ex:
            print(ex, '######################')

    return JsonResponse({'status': True, 'messages': '状态修改失败！'})

def my_view(request):
    queryset = data.objects.filter(stats='s').values_list('soft_version', flat=True)
    return render(request, 'admin/includes/fieldset.html', {'queryset': queryset})